package com.guigu.youxuan.utils;


import com.guigu.youxuan.service.IGatherService;
import com.guigu.youxuan.service.IOrderInfoService;
import com.guigu.youxuan.service.IOutboundService;
import com.guigu.youxuan.service.IPurchaseOrderService;
import com.guigu.youxuan.service.impl.OrderInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class NumberUtils {

    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private IGatherService gatherService;
    @Autowired
    private IOrderInfoService iOrderInfoService;

    @Autowired
    private IOutboundService outboundService;
    /**
     *采购订单编号，格式为100+年月日+4位流水号，例如100202304120009
     * 入库单编号，格式为200+年月日+4位流水号，例如200202204220001
     * 订单编号，格式为300+年月日+4位流水号，例如300202212160003
     * 出库单编号，格式为400+年月日+4位流水号，例如400202304120002
     * @param type 设计单类型编号
     * @return
     */
    public String getTypeNumber(String type) {
        // 拼接类型编号
        StringBuffer buffer = new StringBuffer(type);

        // 当前日期 格式：YYYYMMDD
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(now);
        buffer.append(date);

        // 根据类型获取对应设计单的最大的设计单编号
        String designId = "";
        switch (type) {
            case "100":
                designId = purchaseOrderService.getMaxDesignId();
                break;
            case "200":
                designId = gatherService.getMaxDesignId();
                break;
            case "300":
                designId = iOrderInfoService.getOrderNumber();
                break;
            case "400":
                designId = outboundService.getMaxDesignId();
                break;
        }
        if(designId == null){
            return buffer.append("0001").toString();
        }
        // 获取当前设计单编号的4位流水号  xxxYYYYMMDDxxxx
        String flowNumber = designId.substring(11);
        // 获取当前设计单编号的年份
        String year = designId.substring(3, 7);
        String number = "";
        if(year.equals(date.substring(0,4))) {
            int temp = Integer.parseInt(flowNumber);
            temp ++;
            // 补齐4位字符串
            String newFlowNumber = String.format("%04d", temp);
            number = buffer.append(newFlowNumber).toString();
        } else {
            number = buffer.append("0001").toString();
        }
        return number;
    }
}
